package com.geeksx.trainer.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geeksx.trainer.common.PageRequest;
import com.geeksx.trainer.common.api.Result;
import com.geeksx.trainer.entity.Question;
import com.geeksx.trainer.entity.vo.QuestionVO;
import com.geeksx.trainer.service.KnowledgeCategoryService;
import com.geeksx.trainer.service.QuestionService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 题目接口Controller
 */
@RestController
@RequestMapping("/api/questions")
@RequiredArgsConstructor
public class QuestionController {

    private final QuestionService questionService;

    private final KnowledgeCategoryService knowledgeCategoryService;

    /**
     * 分页查询题目
     * @param pageRequest 分页参数
     * @param type 题目类型，可选
     * @param categoryId 分类ID，可选
     * @return 分页结果
     */
    @GetMapping("/page")
    public Result<Page<QuestionVO>> page(
            PageRequest pageRequest,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Long categoryId) {
        Page<QuestionVO> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
        List<Long> allSubCategoryIds = knowledgeCategoryService.getAllSubCategoryIds(categoryId);
        Page<QuestionVO> resultPage = questionService.pageWithCategoryIds(page, type, allSubCategoryIds);
        return Result.success(resultPage);
    }

    /**
     * 获取题目详情
     */
    @GetMapping("/{id}")
    public Result<Question> getById(@PathVariable Long id){
        return Result.success(questionService.getById(id));
    }

    /**
     * 新增题目
     */
    @PostMapping
    public Result<Boolean> create(@RequestBody Question question){
        return Result.success(questionService.save(question));
    }

    /**
     * 更新题目
     */
    @PutMapping("/{id}")
    public Result<Boolean> update(@PathVariable Long id, @RequestBody Question question){
        question.setId(id);
        return Result.success(questionService.updateById(question));
    }

    /**
     * 删除题目
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id){
        return Result.success(questionService.removeById(id));
    }

    /**
     * 批量删除题目
     */
    @DeleteMapping("/batch-delete")
    public Result<Boolean> batchDelete(@RequestBody List<Long> ids){
        return Result.success(questionService.removeByIds(ids));
    }
}